package com.lemon.service.buy;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.gexin.rp.sdk.base.IPushResult;
import com.lemon.conf.MyException;
import com.lemon.conf.content.IdTypeHandler;
import com.lemon.conf.redis.RedisUtil;
import com.lemon.mapper.cityRun.CrShopOrdersMapper;
import com.lemon.mapper.cityRun.CrShopUserMapper;
import com.lemon.mapper.cityRun.CrShopsMapper;
import com.lemon.mapper.cityRun.CrUserTransactionRecordMapper;
import com.lemon.model.cityRun.CrShopOrders;
import com.lemon.model.cityRun.CrShopSet;
import com.lemon.model.cityRun.CrShopUser;
import com.lemon.model.cityRun.CrShops;
import com.lemon.model.cityRun.CrUserTransactionRecord;
import com.lemon.service.cityRun.CrShopsService;
import com.lemon.service.cityRun.ShopPrintService;
import com.lemon.utils.MD5;
import com.lemon.utils.StringUtil;
import com.lemon.utils.appPush.AppPush;
import com.lemon.utils.pay.AESUtil;
import com.lemon.utils.pay.PayUtil;
import com.lemon.utils.sval.StaticValues;

/**
 * 用户购买课程 相关业务
 *
 * @author hujia
 *         2018年5月17日
 */
@Service
public class BuyServiceImpl implements BuyService {

	private static final Logger logger = LoggerFactory.getLogger(BuyServiceImpl.class);

	@Resource
	private CrShopOrdersMapper orderMapper;
	@Resource
	private ShopPrintService pService;
	@Resource
	private CrShopUserMapper uMapper;
	@Resource
	private CrShopsMapper shopMapper;
	@Resource
	private CrUserTransactionRecordMapper transMapper;
	@Resource
	private CrShopsService shopService;

	/**
	 * <p>
	 * Title: handelRefundNotify
	 * </p>
	 * <p>
	 * Description:(一句话阐述):
	 * </p>
	 * 
	 * @param result
	 * @return
	 * @throws Exception
	 * @author Ran_cc
	 * @date 2018年11月24日
	 */
	@Transactional(noRollbackFor = { Exception.class } , propagation = Propagation.REQUIRED)
	@Override
	public boolean handelRefundNotify(String str) throws Exception {
		logger.info("开始处理成功退款后的操作");
		Map<String , String> resultMap = PayUtil.doXMLParse(str);
		if (!resultMap.get("return_code").equals("SUCCESS"))
			return false;

		String reqInfo = resultMap.get("req_info");
		logger.info("!!!" + reqInfo);
		reqInfo = AESUtil.decryptData(reqInfo);
		logger.info("退款通知解密={}" , reqInfo);
		resultMap = PayUtil.doXMLParse(reqInfo);
		String settlement_refund_fee = resultMap.get("settlement_refund_fee");//退款金额=申请退款金额-非充值代金券退款金额，退款金额<=申请退款金额
		// String refund_fee = resultMap.get("refund_fee");//退款总金额,单位为分
		String success_time = resultMap.get("success_time");
		String refund_status = resultMap.get("refund_status");//SUCCESS-退款成功 CHANGE-退款异常  REFUNDCLOSE—退款关闭
		String transaction_id = resultMap.get("transaction_id");
		String out_refund_no = resultMap.get("out_refund_no");
		String out_trade_no = resultMap.get("out_trade_no");
		//修改订单状态 ,
		logger.info("开始修改订单状态");
		CrShopOrders or = new CrShopOrders();
		or.setOrderNo(out_trade_no);
		or.setStatus(5);
		int row = orderMapper.updateOrderStatByPayOk(or);
		if (row > 0) {

			//添加订单流水线
			or = new CrShopOrders();
			or.setOrderNo(out_trade_no);
			CrShopOrders order = orderMapper.selectBySelective(or);
			CrShopUser u = new CrShopUser();
			u.setWhere(" and b.id = ? " , IdTypeHandler.decode(order.getShopId()));
			CrShopUser user = uMapper.selectBySelective(u);
			//			CrShops cs = new CrShops();
			//			cs.setShopUserId(user.getId());
			//			CrShops shop = shopMapper.selectBySelective(cs);

			//微信支付 生成退款记录 

			CrUserTransactionRecord tran = new CrUserTransactionRecord();
			tran.setSerialNumber(order.getOrderNo());
			tran.setStatus(3);
			tran.setType(2);
			tran.setTranType(1);
			CrUserTransactionRecord record = transMapper.selectBySelective(tran);
			if (record != null) {

				tran.setShopUserId(record.getShopUserId());
				tran.setShopAccount(record.getShopAccount());
				tran.setShopTitle(record.getShopTitle());
				tran.setShopId(record.getShopId());
				tran.setSerialNumber(order.getOrderNo());
				tran.setAmount(record.getAmount());
				tran.setStatus(1);
				tran.setType(1);
				tran.setTranType(1);
				transMapper.insertSelective(tran);

				tran = new CrUserTransactionRecord();
				tran.setId(record.getId());
				tran.setStatus(1);
				transMapper.updateByPrimaryKeySelective(tran);

			}

			/*
			 * CrUserTransactionRecord tran = new CrUserTransactionRecord();
			 * tran.setShopUserId(user.getId());
			 * tran.setShopAccount(user.getUserAccount());
			 * tran.setShopTitle(shop.getShopTitle());
			 * tran.setShopId(shop.getId());
			 * tran.setSerialNumber(out_trade_no);
			 * tran.setAmount(Integer.parseInt(settlement_refund_fee));
			 * tran.setStatus(1);
			 * tran.setType(1);
			 * tran.setTranType(1);
			 * transMapper.insertSelective(tran);
			 */
			//修改账户信息
			/*
			 * u = new CrShopUser();
			 * u.setId(tran.getShopUserId());
			 * u.setAmount(-tran.getAmount());
			 * int selective = uMapper.updateByPrimaryKeySelective(u);
			 */
			//发送信息到app
			try {
				logger.info("开始推送取消消息");
				AppPush push = new AppPush();
				push.setCid(user.getCid());
				push.setContent(out_trade_no);
				push.setTitle("订单取消");
				push.setType(11);
				push.setText("您有一个订单取消,点击查看");
				push.setOrderType(order.getType());
				AppPush.pushMsgToSingle(push);
			} catch (Exception e) {
			}
		}
		return true;
	}

	/**
	 * <p>
	 * Title: payWeChatNotifyUrl
	 * </p>
	 * <p>
	 * Description:(一句话阐述):
	 * </p>
	 * 
	 * @param str
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月24日
	 */
	@Transactional(noRollbackFor = { Exception.class } , propagation = Propagation.REQUIRED)
	@Override
	public boolean payWeChatNotifyUrl(String str) throws Exception {
		logger.info("开始处理成功支付后的操作");
		Map<String , String> map = PayUtil.doXMLParse(str);
		String orderNo = map.get("out_trade_no");
		//修改订单状态 ,
		CrShopOrders or = new CrShopOrders();
		or.setOrderNo(map.get("out_trade_no"));
		or.setStatus(2);
		int row = orderMapper.updateOrderStatByPayOk(or);
		//添加一条财务信息 
		//查询是否已经存在记录
		CrUserTransactionRecord tran = new CrUserTransactionRecord();
		tran.setSerialNumber(map.get("out_trade_no"));
		tran.setStatus(3);
		tran.setType(2);
		tran.setTranType(1);
		CrUserTransactionRecord record = transMapper.selectBySelective(tran);
		logger.info("当前订单[{}]的收益记录:{}" , map.get("out_trade_no") , record);
		if (record == null) {
			or = new CrShopOrders();
			or.setOrderNo(map.get("out_trade_no"));
			CrShopOrders order = orderMapper.selectBySelective(or);
			CrShopUser u = new CrShopUser();
			u.setWhere(" and b.id = ? " , IdTypeHandler.decode(order.getShopId()));
			CrShopUser user = uMapper.selectBySelective(u);
			CrShops cs = new CrShops();
			cs.setShopUserId(user.getId());
			CrShops shop = shopMapper.selectBySelective(cs);
			tran.setShopUserId(user.getId());
			tran.setShopAccount(user.getUserAccount());
			tran.setShopTitle(shop.getShopTitle());
			tran.setShopId(shop.getId());
			tran.setSerialNumber(map.get("out_trade_no"));
			tran.setAmount(Integer.parseInt(map.get("total_fee")));
			//			  tran.setSerialNumber(StringUtil.createSerialNoCityRun());
			tran.setStatus(3);
			tran.setType(2);
			tran.setTranType(1);
			transMapper.insertSelective(tran);
		}

		/*
		 * or = new CrShopOrders();
		 * or.setOrderNo(map.get("out_trade_no"));
		 * CrShopOrders order = orderMapper.selectBySelective(or);
		 * CrShopUser u = new CrShopUser();
		 * u.setWhere(" and b.id = ? " , IdTypeHandler.decode(order.getShopId()));
		 * CrShopUser user = uMapper.selectBySelective(u);
		 * CrShops cs = new CrShops();
		 * cs.setShopUserId(user.getId());
		 * CrShops shop = shopMapper.selectBySelective(cs);
		 * CrUserTransactionRecord tran = new CrUserTransactionRecord();
		 * tran.setShopUserId(user.getId());
		 * tran.setShopAccount(user.getUserAccount());
		 * tran.setShopTitle(shop.getShopTitle());
		 * tran.setShopId(shop.getId());
		 * tran.setSerialNumber(map.get("out_trade_no"));
		 * tran.setAmount(Integer.parseInt(map.get("total_fee")));
		 * tran.setSerialNumber(StringUtil.createSerialNoCityRun());
		 * tran.setStatus(1);
		 * tran.setType(2);
		 * tran.setTranType(1);
		 * transMapper.insertSelective(tran);
		 */
		/*
		 * //修改用户账户信息
		 * u = new CrShopUser();
		 * u.setId(tran.getShopUserId());
		 * u.setAmount(tran.getAmount());
		 * int selective = uMapper.updateByPrimaryKeySelective(u);
		 */

		if (row > 0) {
			//开始打印逻辑,
			//付款之后判断是否自动接单
			new Thread(new Runnable() {
				@Override
				public void run() {
					String orderNo = "";
					try {
						Thread.sleep(5000);
						int row = 0;
						logger.info("另起线程开始打印任务");
						CrShopOrders or = new CrShopOrders();
						or.setOrderNo(map.get("out_trade_no"));
						CrShopOrders order = orderMapper.selectBySelective(or);
						if (order == null) {
							return;
						}

						orderNo = order.getOrderNo();

						CrShopSet set = RedisUtil.get("cityRun:set:set_" + order.getShopId() , CrShopSet.class);

						if (set != null) {
							if (order.getType() == 1) {
								Integer orderOut = set.getGetOrderOut();
								if (orderOut != null && orderOut == 2) {
									//自动接单 状态变成待送达状态
									order.setStatus(3);
								} else {
									//手动接单 状态变成待接单状态
									order.setStatus(2);
								}
							} else {
								//堂食
								Integer orderOut = set.getGetOrderRoom();
								if (orderOut != null && orderOut == 2) {
									//自动接单 状态变成待送达状态
									order.setStatus(3);
									if (order.getPayType() == 1) {
										//微信支付
										//自动接单 状态变成待送达状态
										order.setStatus(31);
										//										order.setStatus(3);
									}
								} else if (orderOut == 3) {
									//微信支付自动接单, 现金结算手动接单
									//判断是微信支付还是手动支付
									if (order.getPayType() == 1) {
										//微信支付
										//自动接单 状态变成待送达状态
										order.setStatus(31);
										//										order.setStatus(3);
									} else {
										//手动接单 状态变成待接单状态
										order.setStatus(2);
									}
								} else {
									//手动接单 状态变成待接单状态
									order.setStatus(2);
								}
							}
							row = orderMapper.updateByPrimaryKeySelective(order);
						}

						try {
							logger.info("开始发送短信到客户端");
							CrShopUser u = new CrShopUser();
							u.setWhere(" and b.id = ? " , IdTypeHandler.decode(order.getShopId()));
							CrShopUser user = uMapper.selectBySelective(u);
							String cid = user.getCid();
							AppPush push = new AppPush();
							push.setCid(cid);
							push.setContent(orderNo);
							push.setTitle("新订单通知");
							//判断是否自动接单
							String t = "";
							if (order.getType() == 1) {
								t = set.getGetOrderOut() + "";
							} else {
								//堂食
								Integer orderOut = set.getGetOrderRoom();
								if (orderOut != null && orderOut == 3) {
									//微信支付自动接单, 现金结算手动接单
									//判断是微信支付还是手动支付
									if (order.getPayType() == 1) {
										//微信支付
										//自动接单 状态变成待送达状态
										t = "2";
									}
								} else {
									//手动接单 状态变成待接单状态
									t = set.getGetOrderRoom() + "";
								}
							}
							logger.info("是否自动接单{}" , t.toString());

							if ("2".equals(t.toString())) {
								push.setType(12);
							} else {
								push.setType(1);
							}
							logger.info("是否自动接单{}" , push.getType());
							push.setText("您有一个新订单,点击查看");
							push.setOrderType(order.getType());
							IPushResult ret = AppPush.pushMsgToSingle(push);
							logger.info(ret.getResponse().toString());
						} catch (Exception e) {
							MyException.writeErr(e , "发送订单短信到app失败");
						}

						if (row > 0) {
							//判断店铺设置是否自动打印()
							if (order.getStatus() == 3 || order.getStatus() == 31 || order.getStatus() == 32) {
								//接单后自动打印小票
								pService.printerInfo(order.getShopId() , order.getId());
							}
							//							Integer printAuto = set.getPrintAuto();
							//							if (printAuto == 1) {
								//自动打印小票  调用打印机 , 内部已经处理打印机列表以及打印机类型 然后自动打印
								//								pService.printerInfo(order.getShopId() , order.getId());
							//							}
						} else {
						}
					} catch (Exception e) {
						MyException.writeErr(e , "打印机打印任务异常:" + orderNo);
					}
				}
			}).start();
		} else {
			return false;
		}
		return true;
	}

	/**
	 * <p>
	 * Title: payWeChatNotifyUrlAppRenewal
	 * </p>
	 * <p>
	 * Description:(一句话阐述):
	 * </p>
	 * 
	 * @param str
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月30日
	 */
	@Transactional(noRollbackFor = { Exception.class } , propagation = Propagation.REQUIRED)
	@Override
	public boolean payWeChatNotifyUrlAppRenewal(String str) throws Exception {
		logger.info("开始处理续费成功后修改到期时间和添加一条交易记录");
		//app 续费成功后添加一条记录
		Map<String , String> map = PayUtil.doXMLParse(str);
		String shopId = map.get("attach");
		//修改店铺的服务到期时间

		CrShops cs = new CrShops();
		cs.setId(shopId);
		CrShops shop = shopMapper.selectShopAndUserById(cs);
		if (shop == null) {
			return false;
		}

		//自动修改成当前截止日期+1年
		Calendar calendar = new GregorianCalendar();
		CrShops cu = new CrShops();
		cu.setId(shop.getId());
		Date serverEndTime2 = shop.getServerEndTime();
		calendar.setTime(serverEndTime2);
		calendar.add(Calendar.YEAR , 1);
		Date serverEndTime = calendar.getTime();
		cu.setServerEndTime(serverEndTime);
		if (StringUtil.DateToString(serverEndTime , 0).equals(StringUtil.DateToString(serverEndTime2 , 0))) {
			logger.info("当前时间已经是最新的续费时间,告诉微信已经处理完毕了");
			return true;
		}
		cu.setShopInCharge(Integer.parseInt(map.get("total_fee")));
		shopMapper.updateByPrimaryKeySelective(cu);
		//修改订单状态 
		CrUserTransactionRecord tran = new CrUserTransactionRecord();
		tran.setShopUserId(shop.getShopUserId());
		tran.setShopAccount(shop.getUserAccount());
		tran.setShopTitle(shop.getShopTitle());
		tran.setShopId(shopId);
		tran.setSerialNumber(map.get("out_trade_no"));
		tran.setAmount(Integer.parseInt(map.get("total_fee")));
		tran.setSerialNumber(StringUtil.createSerialNoCityRun());
		tran.setStatus(1);
		tran.setType(1);
		tran.setTranType(3);
		int i = transMapper.insertSelective(tran);
		//修改用户的入驻费用
		if (i > 0) {
			return true;
		}
		return false;
	}

	/**
	 * <p>
	 * Title: payWeChatNotifyUrlRuzhu
	 * </p>
	 * <p>
	 * Description:(一句话阐述):
	 * </p>
	 * 
	 * @param str
	 * @return
	 * @author Ran_cc
	 * @date 2018年11月30日
	 */
	@Transactional(noRollbackFor = { Exception.class } , propagation = Propagation.REQUIRED)
	@Override
	public boolean payWeChatNotifyUrlRuzhu(String str) throws Exception {
		logger.info("小程序入驻支付成功后回调service...");
		Map<String , String> map = PayUtil.doXMLParse(str);
		String userId = map.get("attach");
		String orderNo = map.get("out_trade_no");
		CrShops shop = RedisUtil.get(RedisUtil.key_before + "newShop:" + userId , CrShops.class);

		if (shop == null) {
			return true;
		}
		CrShops cs = new CrShops();
		cs.setWhere(" and shop_status !=6 and  shop_status !=5 and  shop_status !=0  and b.user_account = ? " ,
				shop.getUserAccount());
		CrShops acc = shopService.selectShopAndUserBySel(cs);
		if (acc != null) {
			return true;
		}

		CrShops s = new CrShops();
		s.setAddressArea(shop.getAddressArea());
		s.setAddressProvince(shop.getAddressProvince());
		s.setAddressCity(shop.getAddressCity());
		s.setAddressInfo(shop.getAddressInfo());
		if (StringUtil.isNotBlank(shop.getAddressLocation())) {
			s.setLongitude(shop.getAddressLocation().split(",")[0]);
			s.setLatitude(shop.getAddressLocation().split(",")[1]);
		}
		s.setServerEndTime(shop.getServerEndTime());
		s.setShopLicense(shop.getShopLicense());
		s.setShopLogo(shop.getShopLogo());
		s.setShopStatus(4);
		s.setShopType(shop.getShopType());
		s.setShopTitle(shop.getShopTitle());
		s.setShopInCharge(shop.getShopInCharge());

		CrShopUser u = new CrShopUser();
		u.setRuleId(IdTypeHandler.encode(StaticValues.RULE_ID_SHOP_USER));
		u.setUserAccount(shop.getUserAccount());
		if (StringUtil.isEmpty(shop.getUserPwd())) {
			String pwd = shop.getUserContact().substring(shop.getUserContact().length() - 6 ,
					shop.getUserContact().length());
			u.setUserPwd(MD5.getMD5("abc123456"));
		}
		u.setUserCardBack(shop.getUserCardBack());
		u.setUserCardFront(shop.getUserCardFront());
		u.setUserContact(shop.getUserContact());
		u.setUserType(2);
		u.setUserWx(shop.getUserWx());
		u.setUserWxName(shop.getUserWxName());
		u.setUserStatus(0);
		u.setUserName(shop.getUserName());
		u.setUserIdCard(shop.getUserIdCard());

		//开始添加数据
		int i = shopService.insertShopsAndSUserInfo(u , s);
		logger.info("添加用户后返回用户的信息:{}" , u.getId());
		//保存用户支付的流水信息
		CrUserTransactionRecord tran = new CrUserTransactionRecord();
		tran.setAmount(shop.getShopInCharge());
		if (StringUtil.isNotBlank(u.getId())) {
			tran.setShopUserId(IdTypeHandler.encode(Long.parseLong(u.getId())));
		}
		tran.setShopAccount(u.getUserAccount());
		tran.setShopTitle(shop.getShopTitle());
		if (StringUtil.isNotBlank(shop.getId())) {
			tran.setShopId(IdTypeHandler.encode(Long.parseLong(u.getId())));
		}
		tran.setSerialNumber(orderNo);
		tran.setStatus(1);
		tran.setType(1);
		tran.setTranType(3);
		transMapper.insertSelective(tran);
		if (i > 1) {
			RedisUtil.del(RedisUtil.key_before + "newShop:" + userId);
			return true;
		}
		return false;
	}
}
